<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\ReceptionUnit;
use app\admin\model\Teacher;
use think\Db;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use app\admin\logic\ZHXY;
use think\Cache;


/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Importschool extends Backend
{
    
    /**
     * Importschool模型对象
     * @var \app\admin\model\Importschool
     */
    protected $model = null;

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    // protected $layout = '';
    protected $searchFields = 'nickname,card_id,tel';

    public function _initialize()
    {
        parent::_initialize();
        // $this->model = new \app\admin\model\Importschool;
        $this->model = new \app\admin\model\Outsideschool;

        //接待单位
        $where = [];
        //测试用部门
        if (!input('admin_test')){
            $where['id'] = ['<>',1];
        }
        $reception_unit = ReceptionUnit::where($where)->where('sort>0')->order('sort')->field("name,id")->select();
        $this->assign('reception_unit', $reception_unit);

        // $this -> whereExtend['is_check'] = 0;
    }   
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index($appids = null)
    {
        // 如果没有缓存跳转登录
        if(empty($appids) && empty($_SESSION['uid'])){
            $url = '/UiZtG6d305.php/index/login?url=%2FUiZtG6d305.php%2Fimportschool%2Findex%2Fappids%2F780';
            header('Location:'.$url);
            die;
        }

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            if($appids=='15610001073'){
                $this -> whereExtend['applier_id'] = '202302175';
            }else{
                $this -> whereExtend['applier_id'] = $appids;
            }
            // if(!empty($appids)){
            //     $teacher = Teacher::get($appids);
            //     $this -> whereExtend['applier_id'] = $teacher['id'];
            // }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where($this -> whereExtend)
                ->where('applier_id>0')
                ->order($sort, $order)
                ->count();

            $list = $this->model 
                ->where($where)
                ->where($this -> whereExtend)
                ->where('applier_id>0')
                ->order($sort, $order)
                ->order('create_time desc')
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $this -> assignConfig('appids',$appids);
        $this -> assignConfig('today',date('Ymd'));
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add($appids = null)
    {
        if ($this->request->isPost()) {
            if(empty($appids)){
                $this->error('当前登录已失效请重新登录');
            }

            $params = $this->request->post("row/a");

            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                $params['is_check'] = -1;
                $params['admission_starttime'] = str_replace('-', '', $params['admission_starttime']);
                $params['admission_endtime'] = str_replace('-', '', $params['admission_endtime']);

                $row = [];
                $where = [];
                $where['card_id'] = $params['card_id'];
                $where['admission_starttime'] = $params['admission_starttime'];
                $where['admission_endtime'] = $params['admission_endtime'];
		
//		        $last_month = strtotime('+1 month',strtotime($params['admission_starttime']));
//                if(strtotime($params['admission_endtime'])>$last_month){
//                    $this->error('入校开始和截止时间间隔不可大于1个月');
//                }
                $last_month = strtotime('+30 day',strtotime($params['admission_starttime']));
                if(strtotime($params['admission_endtime'])>$last_month){
                    $this->error('入校开始和截止时间间隔不可大于30天');
                }
                $find_info = $this->model->where($where)->find();
                if($find_info){
                    $row = $this->model->get($find_info['id']);
                }

                Db::startTrans();
                try {
                    if($appids=='15610001073'){
                        $appids= '202302175';
                        $params['applier_id'] = $appids;
                        $params['applier_name'] = '林 雪 菲';
                    }else{
                        $params['applier_id'] = $appids;
                        $teacher = Teacher::where(['tel'=>$appids])->find();
                        if($teacher){
                            $params['applier_name'] = $teacher['nickname'];
                        }
                    }
                    if($params['reception_id']){
                        $info = ReceptionUnit::get($params['reception_id']);
                        $params['reception_name'] = $info['name'];
                    }
                    if($row){
                        $result = $row->save($params);
                    }else{
                        $result = $this->model->allowField(true)->save($params);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this -> assignConfig('appids',$appids);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params['admission_starttime'] = str_replace('-', '', $params['admission_starttime']);
                $params['admission_endtime'] = str_replace('-', '', $params['admission_endtime']);
//                $last_month = strtotime('+1 month',strtotime($params['admission_starttime']));
//                if(strtotime($params['admission_endtime'])>$last_month){
//                    $this->error('入校开始和截止时间间隔不可大于1个月');
//                }
                $last_month = strtotime('+30 day',strtotime($params['admission_starttime']));
                if(strtotime($params['admission_endtime'])>$last_month){
                    $this->error('入校开始和截止时间间隔不可大于30天');
                }
		        $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    if($params['reception_id']){
                        $info = ReceptionUnit::get($params['reception_id']);
                        $params['reception_name'] = $info['name'];
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    public function check($ids = null){
        $ids = $ids ? $ids : $this->request->param("ids");
        foreach (explode(',',$ids) as $key => $value) {
            $row = $this -> model -> find($value);
            $row->is_check = 0;
            $ret = $row->save();

            if($ret){
                $info = ReceptionUnit::get($row['reception_id']);
                $name_arr = explode(',',$info['nickname']);
                $sid_arr = explode(',',$info['sid']);
                foreach($sid_arr as $key => $v){
                    // if($row['nickname']!='马建华'){
                    //     send_wechat_work_msg([$v], '<a href="https://yqsb.qau.edu.cn/index/outsideschool/view">您有一份校外人员'.$row['applier_name'].'提交的入校预约申请需要审批。</a>');
                    // }
                }

                foreach ($name_arr as $ke => $val) {
                   $name_arr2[] = $val."审批";
                }
                $inst_id = uniqid('outside').mt_rand(100000, 999999);
                $app_id = uniqid('outside').mt_rand(100000, 999999);
                $appname = '校外人员入校';
                $task_id = uniqid('outside').mt_rand(100000, 999999);
                $created_key = 'zhxy_create_' . (string)$app_id;
                $created     = Cache::get($created_key);
                if (!$created) {
                    // 没有创建app
                    $re = $this->push_apps($app_id,$appname);
                    if ($re[0]) {
                        Cache::set($created_key, 1, 3600 * 48);
                    }
                }
                $href_url = 'https://yqsb.qau.edu.cn/index/outsideschool/view';
                $arr['inst_data'] = [[
                    "inst_id"=>$inst_id,
                    "app_id"=>$app_id,
                    "creator"=>$row['applier_id'],
                    "created"=>date('Y-m-d H:i:s'),
                    "finished"=>"",
                    "percent"=>0,
                    "status"=>0,
                    'node_id'=>[$row->id],
                    "node_name"=>$name_arr2,
                    "name"=>"校外人员(".$row['nickname'].")进校申请",
                    "form_url_view"=>$href_url,
                    "form_mobile_url_view"=>$href_url,
                    "thirdparty_id"=>config('zhxy.outside_thirdparty_id'),
                    "process_pic_url"=>"",
                    "conversion_column"=>['app_id','inst_id','node_id','task_id']
                ]];
                $arr['task_data'] = [[
                    "inst_id"=>$inst_id,
                    "app_id"=>$app_id,
                    "task_id"=>$task_id,
                    "node_id"=>$row->id,
                    "status"=>0,
                    "created"=>date('Y-m-d H:i:s'),
                    "finished"=>"",
                    "form_url"=>$href_url,
                    "form_url_view"=>$href_url,
                    "form_mobile_url"=>$href_url,
                    "form_mobile_url_view"=>$href_url,
                    "process_pic_url"=>"",
                    "thirdparty_id"=>config('zhxy.outside_thirdparty_id'),
                    "node_name"=>$info['nickname']."审批",
                    "number"=>$sid_arr,
                    // "node_name"=>"郝老师审批",
                    // "number"=>["200401061"],
                    "conversion_column"=>['app_id','inst_id','node_id','task_id']
                ]];
                $url  = config('zhxy.push-task');
                $data =  $this->send_zhxy_msg($url,$arr,'outside');
                if($data[0] && $data[1]=='发送成功'){
                    $outside_zhxy = [
                        'inst_id'=>$inst_id,
                        'app_id'=>$app_id,
                        'task_id'=>$task_id,
                    ];
                    Db::name('outsideschool')->where('id',$row->id)->update(['outside_zhxy_json'=>json_encode($outside_zhxy)]);
                }
            }


            // if($ret){
            //     // // 将当前的信息提交到正式库，让学院领导审核
            //     // $insert = [
            //     //     'applier_id'=>Teacher::where('id',$row->applier_id)->value('tel'),
            //     //     'applier_name'=>$row->applier_name,
            //     //     'nickname'=>$row->nickname,
            //     //     'card_id'=>$row->card_id,
            //     //     'tel'=>$row->tel,
            //     //     'work_unit'=>$row->work_unit,
            //     //     'memo'=>$row->memo,
            //     //     'admission_starttime'=>date('Ymd',$row->admission_starttime),
            //     //     'admission_endtime'=>date('Ymd',$row->admission_endtime),
            //     //     'reception_id'=>$row->reception_id,
            //     //     'reception_name'=>$row->reception_name,
            //     //     'car_number'=>$row->car_number,
            //     //     'is_uncomfortable'=>0,
            //     //     'importschool_id'=>$row->id,
            //     //     'create_time'=>time(),
            //     //     'update_time'=>time(),
            //     // ];
            //     // $res = Db::name('outsideschool')->insert($insert);
            //     // 给审核人员发送短信
            //     if($res) {
            //         $info = ReceptionUnit::get($row->reception_id);
            //         $sid_arr = explode(',',$info->sid);
            //         // foreach($sid_arr as $key => $v){
            //         //     send_wechat_work_msg([$v], '<a href="https://yqsb.qau.edu.cn/index/outsideschool/view">您有一份校外人员'.$row->applier_name.'提交的入校预约申请需要审批。</a>');
            //         // }
            //     }
            // }
        }
        $this->success();
    }

    /**
     * 复制以前的入校记录，重新编辑入校时间
     * [recheck description]
     * @param  [type] $ids [description]
     * @return [type]      [description]
     */
    public function recheck($ids = null){
        $ids = $ids ? $ids : $this->request->param("ids");
        foreach (explode(',',$ids) as $key => $value) {
            $import_info = Db::name('outsideschool')->where('id',$value)->find();
            unset($import_info['id']);
            $import_info['is_check'] = -1;
            $import_info['admission_starttime'] = $import_info['admission_endtime'] = date('Ymd');
            $import_info['create_time'] = $import_info['update_time'] = time();
            $import_info['check_time'] = $import_info['check_sid'] = $import_info['check_cn'] ='';
            $import_info['use_time'] = $import_info['use_time_record'] = $import_info['gate_name'] ='';
            $import_info['is_use'] = 0;
            $import_info['gate_id'] = 0;
            $import_info['is_outside_zhxy'] = 0;
            $import_info['outside_zhxy_json'] = '';
            Db::name('outsideschool')->insert($import_info);
        }
        $this->success('操作成功,请在待处理列表编辑','',[],10);
    }
    /**
     * 撤销提交
     * [back description]
     * @param  [type] $ids [description]
     * @return [type]      [description]
     */
    public function back($ids = null){
        $ids = $ids ? $ids : $this->request->param("ids");
        foreach (explode(',',$ids) as $key => $value) {
            // $outsides = Db::name('outsideschool')->where('id',$value)->where('importschool_id>0')->find();
            // if($outsides['is_check']>0){
            //     $this->error('预约申请已审批不可撤回');
            //     continue;
            // }
            // if($outsides){
            //     Db::name('outsideschool')->where('importschool_id',$value)->where('importschool_id>0')->delete();
            // }
            $row = $this -> model -> get($value);
            if(!empty($row['outside_zhxy_json'])){
                $outside = json_decode($row['outside_zhxy_json'],true);
                $app_id  = $outside['app_id'];
                $inst_id = $outside['inst_id'];
                $task_id = $outside['task_id'];

                $arr['inst_data'] = [[
                    "inst_id"=>$inst_id,
                    "app_id"=>$app_id,
                    "creator"=>$row['applier_id'],
                    "created"=>date('Y-m-d H:i:s',$row['create_time']),
                    "finished"=>date('Y-m-d H:i:s'),
                    "percent"=>100,
                    "status"=>2,
                    'node_id'=>[$row['id']],
                    "node_name"=>[$row['applier_name']],
                    "name"=>"校外人员(".$row['nickname'].")进校申请",
                    "form_url_view"=>"",
                    "form_mobile_url_view"=>"",
                    "thirdparty_id"=>config('zhxy.outside_thirdparty_id'),
                    "process_pic_url"=>"",
                    "conversion_column"=>['app_id','inst_id','node_id','task_id']
                ]];
                $arr['task_data'] = [[
                    "inst_id"=>$inst_id,
                    "app_id"=>$app_id,
                    "task_id"=>$task_id,
                    "node_id"=>$row['id'],
                    "status"=>3,
                    "created"=>date('Y-m-d H:i:s',$row['create_time']),
                    "finished"=>date('Y-m-d H:i:s'),
                    "form_url"=>"",
                    "form_url_view"=>"",
                    "form_mobile_url"=>"",
                    "form_mobile_url_view"=>"",
                    "process_pic_url"=>"",
                    "thirdparty_id"=>config('zhxy.outside_thirdparty_id'),
                    "node_name"=>$row['applier_name'],
                    "number"=>[$row['applier_id']],
                    "conversion_column"=>['app_id','inst_id','node_id','task_id']
                ]];
                $url  = config('zhxy.push-task');
                $data2 =  $this->send_zhxy_msg($url,$arr,'outside');
                if($data2[0] && $data2[1]=='发送成功'){
                    Db::name('outsideschool')->where(['id'=>$row['id']])->update(['is_outside_zhxy'=>1]);
                }
            }
            $row->is_check = -1;
            $ret = $row->save();


        }
        $this->success();
    }

    /**
     * [uselist description]
     * @param  [type] $ids [description]
     * @return [type]      [description]
     */
    public function uselist($ids = null){
        $row = $this -> model -> get($ids);
        if(!$row){
            $this->error(__('No Results were found'));
        }
        $use_time_record = str_replace("[","",$row['use_time_record']);
        $use_time_record = str_replace("]","",$use_time_record);
        $row['use_time_record'] = explode(',',$use_time_record);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /**
     * 导入
     */
    public function import($appids = null)
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 2; $currentRow <= 2; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 3; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }
                if ($row) {
                    $insert[] = $row;
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }
        $idcard_str = '';  //身份证不合理
        $duplicate_rows = []; // 重复数据（行）（比较数据库中数据）
        if(empty($appids)){
            $this->error('当前登录已失效请重新登录');
        }
        try {
            $error = 0;
            $error_str = '';
            foreach ($insert as $key => $value) {
                if(!empty($value['card_id'])){
                    $insert[$key]['is_check'] = -1;
                    if($appids=='15610001073'){
                        $appids= '202302175';
                        $insert[$key]['applier_id'] = $appids;
                        $insert[$key]['applier_name'] = '林 雪 菲';
                    }else{
                        $insert[$key]['applier_id'] = $appids;
                        $teacher = Teacher::where(['tel'=>$appids])->find();
                        if($teacher){
                            $params['applier_name'] = $teacher['nickname'];
                        }
                        $teacher = Teacher::where(['tel'=>$appids])->find();
                        if($teacher){
                            $insert[$key]['applier_name'] = $teacher['nickname'];
                        }
                    }
                    if(empty($value['nickname'])){
                        $error = 10;
                        $error_str .= '<span class="text-danger">表格第'.($key+3).'行:姓名不可为空</span><br/>';
                    }
                    if(empty($value['tel'])){
                        $error = 10;
                        $error_str .= '<span class="text-danger">表格第'.($key+3).'行,姓名:'.$value['nickname'].',手机号不可为空</span><br/>';
                    }else{
                        // if(!$this->checkMobileValidity($value['tel'])){
                        //     $error = 1;
                        //     $error_str .= '<span class="text-danger">表格第'.($key+3).'行：手机号格式不正确</span><br/>';
                        // }
                        if(!$this->validatePhoneno($value['tel'])){
                            $error = 1;
                            $error_str .= '<span class="text-danger">表格第'.($key+3).'行,姓名:'.$value['nickname'].',手机号格式不正确</span><br/>';
                        }
                    }
                    
                    // @date 2022/9/9 ywg 剔除身份证中非字符、数字的字符
                    $insert[$key]['card_id'] = preg_replace('/[^0-9a-zA-Z]/', '', $value['card_id']);
                    $idcard_cn = trim(strtoupper($insert[$key]['card_id']));
                    $idc=$this->is_idcard($idcard_cn);
                    if(!$idc){
                        $error = 2;
                        $error_str .= '<span class="text-danger">表格第'.($key+3).'行,姓名:'.$value['nickname'].',身份证格式错误</span><br/>';
                    }
                    
                    if(empty($value['work_unit'])){
                        $error = 10;
                        $error_str .= '<span class="text-danger">表格第'.($key+3).'行,姓名:'.$value['nickname'].',工作单位不可为空</span><br/>';
                    }
                    if(empty($value['memo'])){
                        $error = 10;
                        $error_str .= '<span class="text-danger">表格第'.($key+3).'行,姓名:'.$value['nickname'].',访问事由不可为空</span><br/>';
                    }
                    // if(empty($value['car_number'])){
                    //     $error = 10;
                    //     $error_str .= '<span class="text-danger">表格第'.($key+3).'行,姓名:'.$value['nickname'].',车牌号不可为空</span><br/>';
                    // }
                    if(empty($value['reception_name'])){
                        $error = 10;
                        $error_str .= '<span class="text-danger">表格第'.($key+3).'行,姓名:'.$value['nickname'].',接待单位不可为空</span><br/>';
                    }
                    
                    if(empty($value['admission_starttime'])){
                        $error = 3;
                        $error_str .= '<span class="text-danger">表格第'.($key+3).'行,姓名:'.$value['nickname'].',入校开始时间不可为空</span><br/>';
                    }else{
                        if(strlen(strtotime($value['admission_starttime']))!=10){
                            $error = 4;
                            $error_str .= '<span class="text-danger">表格第'.($key+3).'行,姓名:'.$value['nickname'].',入校开始时间格式错误</span><br/>';
                        }
                    }
                    if(empty($value['admission_endtime'])){
                        $error = 5;
                        $error_str .= '<span class="text-danger">表格第'.($key+3).'行,姓名:'.$value['nickname'].',入校截止时间不可为空</span><br/>';
                    }else{
                        if(strlen(strtotime($value['admission_endtime']))!=10){
                            $error = 6;
                            $error_str .= '<span class="text-danger">表格第'.($key+3).'行,姓名:'.$value['nickname'].',入校截止时间格式错误</span><br/>';
                        }
                        $last_month = strtotime('+30 day',strtotime($value['admission_starttime']));
                        if(strtotime($value['admission_endtime'])>$last_month){
                            $error = 7;
                            $error_str .= '<span class="text-danger">表格第'.($key+3).'行,姓名:'.$value['nickname'].',入校开始和截止时间间隔不可大于30天</span><br/>';
                        }
                    }
                    $unit = ReceptionUnit::where(['name'=>$value['reception_name']])->find();
                    if($unit){
                        $insert[$key]['reception_id'] = $unit['id'];
                    }
                    $insert[$key]['admission_starttime'] = date('Ymd',strtotime($value['admission_starttime']));
                    $insert[$key]['admission_endtime'] = date('Ymd',strtotime($value['admission_endtime']));
                    if($error>0){
                        $this->error($error_str);
                    }
                    // 查重
                    $dup_where = [
                        'card_id' => $value['card_id'],
                        'admission_starttime' => date('Ymd',strtotime($value['admission_starttime'])),
                        'admission_endtime' => date('Ymd',strtotime($value['admission_endtime'])),
                        'is_check'=>-1
                    ];
                    if ($this->model->where($dup_where)->count()) {
                        $duplicate_rows[] = $insert[$key];
                        unset($insert[$key]);
                        continue;
                    }
                }else{
                    unset($insert[$key]);
                }
            }
            // 没有错误导入
            if($error ==0){
                $this->model->saveAll($insert);
            }
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        if(!empty($duplicate_rows) ){
            $msg = '<span class="text-success">导入成功</span><br/>';
            if (!empty($duplicate_rows)) {
                $msg .= '以下数据已存在，没有导入:<br />';
                foreach ($duplicate_rows as $ritem) {
                    $msg .= '<span class="text-danger">'.$ritem['nickname'] . '：' . $ritem['card_id'] . '</span><br />';
                }
            }
            $this->success($msg);
        }else{
            $this->success('导入成功');
        }

    }



    /**
     * 生成appid 事项id
     * [push_apps description]
     * @param  [type] $appid   [description]
     * @param  [type] $appname [description]
     * @return [type]          [description]
     */
    public function push_apps($appid, $appname)
    {
        $url        = config('zhxy')['push-apps'];
        $conversion = true;
        $data       = [
            'conversion' => $conversion,
            'apps'       => [
                [
                    'id'            => $appid,
                    'name'          => $appname,
                    'thirdparty_id' => config('zhxy.outside_thirdparty_id'),
                ]
            ],
        ];
        $re = $this->send_zhxy_msg($url, $data,'outside');
        if (!$re[0]) {
            return 'error';
        }
        return $re;
    }


    /**
     * 
     * [send_zhxy_msg description]
     * @param  [type] $url       [description]
     * @param  [type] $post_data [description]
     * @param  [type] $type      [description]
     * @return [type]            [description]
     */
    private function send_zhxy_msg($url, $post_data,$type = null)
    {
        $token         = (new \app\admin\logic\zhxy\GetAccessToken())->get_token($type);
        if(!$token){
            return 'token is null';
        }
        $domain  = config('zhxy.school_url');
        $urlFull = $domain . $url . '?access_token=' . $token;
        $data = json_post($urlFull, $post_data);
        $res = json_decode($data, true);
        if ($res['e'] == 0) {
            return [ true, '发送成功', $res ];
        }
        return [ false, $res['m'], $res ];
    }



    /**
     * 检查身份证是否正常
     */
    public function check_idcard()
    {
        $params = $this->request->post("row/a");
        if (isset($params['card_id'])) {
            $idcard = $params['card_id'];
        } else {
            $idcard = $this->request->post('card_id', '');
        }
        $ret=$this->is_idcard($idcard);
        if ($ret) {
            $this->success();
        } else {
            $this->error('该身份证号不正确，请重新输入');
        }
    }

    /********************php验证手机号是否正确函数*********************/

     /**
     *  验证手机号
     * @param  [type] $tel [description]
     * @return [type]      [description]
     */
    function validatePhoneno($tel){
        //正则表达式 
        if(strlen($tel) == "11"){ 
            //上面部分判断长度是不是11位 
            $n = preg_match_all("/13[123569]{1}\d{8}|15[1235689]\d{8}|188\d{8}/",
            $tel,$array); 
            /*接下来的正则表达式("/131,132,133,135,136,139开头随后跟着任意的8为数字 '|
            '(或者的意思) 
             * 151,152,153,156,158.159开头的跟着任意的8为数字 
             * 或者是188开头的再跟着任意的8为数字,匹配其中的任意一组就通过了 
             * /")*/
            if (empty($array)) {
                return false;
            }

            return true;
        }else{ 
            return false;
        } 
    }

    function checkMobileValidity($mobilephone){
        $exp = "/^13[0-9]{1}[0-9]{8}$|15[012356789]{1}[0-9]{8}$|18[012356789]{1}[0-9]{8}$|14[57]{1}[0-9]$/";
        if(preg_match($exp,$mobilephone)){
            return true;
        }else{
            return false;
        }
    }


    /********************php验证身份证号码是否正确函数*********************/

    function is_idcard( $id )
    {
        $id = strtoupper($id);
        $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
        $arr_split = array();
        if(!preg_match($regx, $id))
        {
            return FALSE;
        }
        if(15==strlen($id)) //检查15位
        {
            $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";
          
            @preg_match($regx, $id, $arr_split);
            //检查生日日期是否正确
            $dtm_birth = "19".$arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4];
            if(!strtotime($dtm_birth))
            {
              return FALSE;
            } else {
              return TRUE;
            }
        }else {     //检查18位
            $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
            @preg_match($regx, $id, $arr_split);
            $dtm_birth = $arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4];
            if(!strtotime($dtm_birth)) //检查生日日期是否正确
            {
              return FALSE;
            }
            else
            {
              //检验18位身份证的校验码是否正确。
              //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
              $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
              $arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
              $sign = 0;
              for ( $i = 0; $i < 17; $i++ )
              {
                // $b = (int) $id{$i};
                $b = (int) $id[$i];
                $w = $arr_int[$i];
                $sign += $b * $w;
              }
              $n = $sign % 11;
              $val_num = $arr_ch[$n];
              if ($val_num != substr($id,17, 1))
              {
                return FALSE;
              } //phpfensi.com
              else
              {
                return TRUE;
              }
            }
        } 
    }



}
